package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWeMediaClient;
import com.heima.article.mapper.ArticleHomeMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    private IWeMediaClient weMediaClient;
    @Autowired
    private ArticleHomeMapper mapper;
    @Autowired
    private CacheService service;

    @Override
    public void hotArticle() {
        //获取前5天文章
        Date dateParam= DateTime.now().minusDays(20).toDate();
        List<ApArticle> apArticles = mapper.loadArticle5day(dateParam);
        //添加分值之后的所有文章
        List<HotArticleVo> hotArticleVos=getScore(apArticles);
        //根据分值为每个频道缓存30篇文章
        cacheArticle(hotArticleVos);
    }

    /**
     * 缓存数据
     * @param hotArticleVos
     */
    private void cacheArticle(List<HotArticleVo> hotArticleVos) {
        ResponseResult responseResult = weMediaClient.getChannel();
        if (responseResult.getCode()==200){
            String jsonString = JSON.toJSONString(responseResult.getData());
            List<WmChannel> wmChannels = JSON.parseArray(jsonString, WmChannel.class);

            if (wmChannels!=null&&wmChannels.size()>0){
                for (WmChannel wmChannel : wmChannels) {
                    //将频道相同的放到一个集合
                    List<HotArticleVo> articleVos = hotArticleVos.stream()
                            .filter(s -> s.getChannelId().equals(wmChannel.getId())).collect(Collectors.toList());
                    //排序并保存到缓存
                    sortAndCache(articleVos,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+wmChannel.getId());
                }
            }
        }
        //默认频道
        sortAndCache(hotArticleVos,ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);
    }
    //排序并且保存到缓存
    private void sortAndCache(List<HotArticleVo> articleVos, String key) {
        articleVos = articleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore)
                .reversed()).collect(Collectors.toList());
        if (articleVos.size()>30){
            articleVos = articleVos.subList(0, 30);
        }
        service.set(key,JSON.toJSONString(articleVos));
    }

    /**
     * 获得添加分值之后的所有文章
     * @param apArticles
     * @return
     */
    private List<HotArticleVo> getScore(List<ApArticle> apArticles) {
        List<HotArticleVo> articleVos=new ArrayList<>();
        if (apArticles!=null&&apArticles.size()>0){
            //遍历每一篇文章  进行算分
            for (ApArticle apArticle : apArticles) {
                HotArticleVo articleScore = getArticleScore(apArticle);
                articleVos.add(articleScore);
            }
        }
        return articleVos;
    }

    /**
     * 获取每篇文章分值
     * @param apArticle
     */
    private HotArticleVo getArticleScore(ApArticle apArticle) {
        HotArticleVo hotArticleVo=new HotArticleVo();
        BeanUtils.copyProperties(apArticle,hotArticleVo);
        int score=0;
        //点赞数量
        Integer likes = apArticle.getLikes();
        if (likes!=null){
            score+=likes * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        //评论数量
        Integer comment = apArticle.getComment();
        if (comment!=null){
            score += comment * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        //查看数量
        Integer views = apArticle.getViews();
        if (views!=null){
            score += views;
        }
        //收藏数量
        Integer collection = apArticle.getCollection();
        if (collection!=null){
            score += collection * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        hotArticleVo.setScore(score);
        return hotArticleVo;
    }
}
